# -*- coding: utf-8 -*-
from datetime import datetime
import os

from util import get_time

per = 15  # 15 秒计算一次


def check_dir(source):
    ls = []
    for dir in os.listdir(source):
        ls.append(os.path.join(source, dir))
    ls.sort()
    return ls


def check_file(basedir):
    ls = []
    for filename in os.listdir(basedir):
        ls.append(os.path.join(basedir, filename))
    ls.sort()
    return ls


def get_ip_method(filename):
    basename = os.path.basename(filename)
    filet = basename.split('_')

    ip = filet[0]  # ip
    dnum = filet[1]  # 编号
    time = filet[2]  # 时间
    action = "_".join(filet[3:]).split('.')[0]

    return ip, dnum, time, action


def get_day(ip, dum, tm):
    return (ip, dum, get_time(tm).strftime("%Y%m%d"))


def get_key(ip, dum, tm, action, per_time, first):
    key = "{}{}".format(int((get_time(tm)-get_time(first)).total_seconds()/per_time), action)
    return key


def get_dict(source, per_time, send_trigger_nums=4, window_time=20):
    res = dict()
    first = dict()
    for path in check_dir(source):
        for filename in check_file(path):
            ip, dum, tm, action = get_ip_method(filename)
            day = get_day(ip, dum, tm)
            if not res.get(day):
                res[day] = dict()
                first[day] = tm
            # 获取key的时候不需要action
            key = get_key(ip, dum, tm, action, per_time, first[day])
            if not res[day].get(key):
                res[day][key] = list()
            if (abs((datetime.now() - get_time(tm)).total_seconds()) >= window_time):
                if len(res[day][key]) < send_trigger_nums:
                    res[day][key].append(filename)
            else:
                res[day].pop(key)
    return res
